//
//  WmcScriptHandler.swift
//  YPWatermarkCamera
//
//  Created by Json on 2023/7/25.
//

import UIKit
import YPBedrock
import WebKit

class WmcScriptHandler: NSObject {
    typealias WmcHandler = (_ params: [String: Any]) -> Void
    weak var webView: WKWebView?
    private lazy var handlers: [String: WmcHandler] = [:]
    
    // MARK: Init
    init(webView: WKWebView) {
        self.webView = webView
        super.init()
    }

    
    // MARK: Public method
    /// 方法注册(原生注册,h5调用)
    /// - Parameters:
    ///   - method: 方法名
    ///   - handler: 方法对应的调用
    func register(method: String, handler: @escaping WmcHandler) {
        if method.isEmpty { return }
        webView?.configuration.userContentController.add(self, name: method)
        handlers[method] = handler
    }
    
    /// 方法调用(h5注册,原生调用)
    /// - Parameters:
    ///   - method: 方法名
    ///   - params: 参数
    ///   - completion: 调用结果回调
    func call(method: String, params: Any? = nil, completion: ((Any?) -> Void)? = nil) {
        if method.isEmpty { return }
        var jsFunction = method + "()"
        if let params = params {
            jsFunction = method + "(\(params))"
        }
        webView?.evaluateJavaScript(jsFunction, completionHandler: { data, error in
            if let err = error {
                print(err.localizedDescription)
            } else {
                completion?(data)
            }
        })
    }
    
    /// 清除h5调用原生方法调用
    func clearMessageHandlers() {
        for (name, _) in handlers {
            webView?.configuration.userContentController.removeScriptMessageHandler(forName: name)
        }
        handlers.removeAll()
    }
    
    deinit {
        print("RwaScriptHandler被销毁")
    }

}

// MARK: WKScriptMessageHandler
extension WmcScriptHandler: WKScriptMessageHandler {
   
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let handler = handlers[message.name]
        let body = message.body as? [String: Any] ?? [:]
        print("JS调用原生方法: \(message.name); 参数: \(body)")
        handler?(body)
    }
}
